<template>
	<div style="width: 100vw;height: 100vh;display: flex;flex-direction: row;background-color:#caf7e3 ;">
		<div id="container" style="height: 100vh;width: 27vw;" class="border">

		</div>

		<div style="width: 39vw;height: 100vh;display: flex;flex-direction: column;margin-left: 1vw;" class="border">
			<div style="width: 100%;margin-top: 1vh; height: 5%;display: flex;flex-direction: row; justify-content: space-around;">
				<div>
					<el-select v-model="value" placeholder="请选择">
						<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</div>

				<div>
					<el-button @click='select'>查询</el-button>
				</div>
				<div style="display: flex;flex-direction: row-reverse;align-items: center;">
					<el-switch @change="starORdirt" v-model="starORdirtvalue" active-text="导演" inactive-text="演员">
					</el-switch>
				</div>
			</div>

			<div id="ndge" style="width: 100%;height: 55%;margin-top: 1vh;"></div>

			<div id="cloud" :data="cloudMsg" style="width: 100%;height: 40%;"></div>
		</div>
		<div style="width:29vw ;height: 100vh;display: flex;flex-direction: column;margin-left: 2vw;">
			<div class="border" id="exchange" style="width: 100%;height: 50vh;"></div>
			<div style="width: 100%;height: 50vh;display: flex;flex-direction: row;">
				<div class="border" id="sort" style="width: 90%;height: 50vh;"></div>
				<div class="border" style="width: 8%;height: 100%;display: flex;flex-direction:column;">
					<div>
						<el-button size="mini" icon="el-icon-minus" @click="decrease"></el-button>
					</div>
					<div style="border: 0.03825rem solid  #afafaf; width: 42px;height: 20px;display: flex;justify-content: center;align-items: center;">
						<div style="color: #565656;">{{num}}</div>
					</div>
					<div>
						<el-button size="mini" icon="el-icon-plus" @click="increase"></el-button>
					</div>
				</div>
			</div>

		</div>



	</div>
</template>

<script>
	//import wordcloud from "echarts-wordcloud";
	import "echarts-wordcloud/dist/echarts-wordcloud";
	import "echarts-wordcloud/dist/echarts-wordcloud.min";
	import axios from 'axios';
	import * as echarts from "echarts";
	import $ from 'jquery'; //在需要使用的页面中
	export default {
		data() {
			return {
				starORdirtvalue: false,
				opinionData1: ["3", "2", "4", "4", "5", "8", "3"],
				num: 10,
				//选框
				options: [{
						value: '2020-07',
						label: '2020-07'
					}, {
						value: '2020-08',
						label: '2020-08'
					}, {
						value: '2020-09',
						label: '2020-09'

					}, {
						value: '2020-10',
						label: '2020-10'
					}, {
						value: '2020-11',
						label: '2020-11'
					},
					{
						value: '2020-12',
						label: '2020-12'
					}, {
						value: '2021-01',
						label: '2021-01'
					}, {
						value: '2021-02',
						label: '2021-02'
					}, {
						value: '2021-03',
						label: '2021-03'
					}, {
						value: '2021-04',
						label: '2021-04'
					},{
						value: '2021-05',
						label: '2021-05'
					}
					
				],
				value: '2021-04',

				Each_dayData: {},
				Movie_sell_day: {},
				cloudMsg: [],
				star:{},
				dirt:{},
			}
		},
		mounted() {
			this.exchangeBoxoOffice(this.$data.Each_dayData);
			this.drawSort(this.$data.Movie_sell_day);

			this.getTop50(this.$data.value, 30, this.$data.starORdirtvalue);
			this.getMovie_sell_day(this.$data.value);
			this.getEach_day(this.$data.value);
			this.getMovie(this.$data.value);
			this.getCloudMsg();
			this.cloud(this.$data.cloudMsg);
		},
		methods: {
			select() {
				let data = ''
				console.log(this.$data.value)
				
				this.getTop50(this.$data.value, 30, this.$data.starORdirtvalue)
				this.getEach_day(this.$data.value)
				this.getMovie_sell_day(this.$data.value)
				
				this.getMovie(this.$data.value)
				this.cloud(this.$data.cloudMsg)
			},
			//导演与演员
			starORdirt() {
				console.log("点击了导演与演员！！" + this.$data.starORdirtvalue)
				this.getTop50(this.$data.value, 30, this.$data.starORdirtvalue);
				this.cloud(this.$data.cloudMsg)
			},
			//获取该月电影票房排行
			getMovie_sell_day(time) {
				let vue = this;
				axios.get('http://47.93.220.108:8000/api/v1/movie/movie_sell_day', {
						params: {
							date: time
						}
					})
					.then(response => {
						if (response.data.msg == 'success') {

							console.log("获取该月电影票房排行成功")
							console.log(response)
							this.getPart(response.data.res, this.$data.num)
							this.drawSort(this.$data.Movie_sell_day)
						} else {
							console.error("获取机器列表失败")
						}
					})
			},


			//获取top50导演明星
			getTop50(time, num, starORdirtvalue) {
				let vue = this;
				axios.get('http://47.93.220.108:8000/api/v1/movie/top50', {
						params: {
							date: time,
							num: num,
						}
					})
					.then(response => {
						if (response.data.msg == 'success') {

							console.log("获取top50成功")
							console.log(response)
							if (starORdirtvalue == false) {
								// var that = this
								// setTimeout(function () {
								//    that.drawNdge(response.data.res.star.slice(0, 14))
								   
								// },1000);
								
								this.drawNdge(response.data.res.star.slice(0, 14))
							}
							if (starORdirtvalue == true) {
								
								// var that = this
								// setTimeout(function () {
								//    that.drawNdge(response.data.res.dir.slice(0, 14))
								   
								// },1000);
								
								this.drawNdge(response.data.res.dir.slice(0, 14))
							}

						} else {
							console.error("获取机器列表失败")
						}
					})
			},

			//获取该月按天票房变化
			getEach_day(time) {
				let vue = this;
				axios.get('http://47.93.220.108:8000/api/v1/movie/each_day', {
						params: {
							date: time,
						}
					})
					.then(response => {
						if (response.data.msg == 'success') {
							console.log("获取该月按天票房变化成功")
							console.log(response)
							vue.$data.Each_dayData = response.data.res;
							this.exchangeBoxoOffice(response.data.res);
						} else {
							console.error("获取机器列表失败")
						}
					})
			},

			//票房变化图渲染
			exchangeBoxoOffice(data) {
				echarts.init(document.getElementById("exchange")).setOption({
					tooltip: {
						trigger: 'axis',
						position: function(pt) {
							return [pt[0], '10%'];
						}
					},
					title: {
						left: 'left',
						text: this.$data.value + '票房变化',
					},
					grid: {
						left: '1%',

						containLabel: true
					},

					xAxis: {
						type: 'category',
						boundaryGap: false,
						data: Object.keys(data),
					},
					yAxis: {
						type: 'value',
						boundaryGap: [0, '30%']
					},
					dataZoom: [{
						type: 'inside',
						start: 0,
						end: 100
					}, {
						start: 0,
						end: 100
					}],
					series: [{
						name: '该天票房',
						type: 'line',
						symbol: 'none',
						sampling: 'lttb',
						itemStyle: {
							color: 'rgb(255, 70, 131)'
						},
						areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
								offset: 0,
								color: 'rgb(255, 158, 68)'
							}, {
								offset: 1,
								color: 'rgb(255, 70, 131)'
							}])
						},
						data: Object.values(data)
					}]

				})

			},
			//该月电影票房排行
			drawSort(data) {
				echarts.init(document.getElementById("sort")).setOption({
					title: {
						text: this.$data.value + '票房排行榜',
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						}
					},
					grid: {
						left: '0%',
						right: '0%',
						bottom: '0%',
						containLabel: true
					},
					xAxis: {
						type: 'value',
						boundaryGap: [0, 0.01]
					},
					yAxis: {
						type: 'category',
						data: Object.keys(data)
					},
					series: {
						type: 'bar',
						data: Object.values(data)
					},
				})
			},


			drawNdge(data) {
				echarts.init(document.getElementById("ndge")).setOption({
					title: {
						text: '明星票房排行',
					},
					legend: {
						top: 'bottom'
					},
					grid: {
						containLabel: true
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						}
					},

					series: [{
						name: '面积模式',
						type: 'pie',
						radius: [20, 100],
						center: ['50%', '50%'],
						roseType: 'area',
						itemStyle: {
							borderRadius: 8
						},
						data: data
					}]
				});
			},

			getPart(data, sum) {
				var newData = {}
				var newDatas = {}
				let newKeys = Object.keys(data)
				newKeys.map((item, idx) => {
					if (idx < sum) {
						newData[item] = data[item]
					}
				})
				for (let key in newData) {
					let newKey = key.substring(0, sum - 1)
					newDatas[newKey] = newData[key]
				}
				this.$data.Movie_sell_day = newDatas;
				console.log(newDatas)

			},
			decrease() {
				if(this.$data.num >= 2){
					this.$data.num--;
				}
				
				this.getMovie_sell_day(this.$data.value)
			},
			increase() {
				this.$data.num++;
				this.getMovie_sell_day(this.$data.value)
			},

			

			getMovie(time) {
				var myChart = echarts.init(document.getElementById('container'));
				var app = {};
				myChart.showLoading();	
				var option;


				var Time = time;
				var updateFrequency = 1000;
				var dimension = 0;
				
				
				$.get('http://47.93.220.108:8000/api/v1/movie/rank?date=' + time, function(res) {
					// console.log("res="+res);
					var data = res[1];
					// console.log("data="+data);
					var countryColors = res[0];
					// console.log("countryColors="+countryColors);
					var years = [];
					// 读入时间

					for (var i = 0; i < data.length; ++i) {
						if (years.length === 0 || years[years.length - 1] !== data[i][2]) {
							years.push(data[i][2]);
						}
					}
					console.log(years);
					// 设置开始时间的角标
					var startIndex = 0;
					// 设置开始时间
					var startYear = years[startIndex];

					var option = {

						grid: {
							top: 40,
							bottom: 40,
							// grid 组件离容器左侧的距离
							left: 150,
							right: 60
						},
						xAxis: {
							name: '票房/万',
							// 坐标轴刻度最大值
							// 可以设置成特殊值 'dataMax'，此时取数据在该轴上的最大值作为最大刻度。
							max: 'dataMax',
							label: {
								formatter: function(n) {
									return Math.round(n);
								}
							}
						},
						dataset: {
							source: data.filter(function(d) {
								return d[2] === startYear;
							})
						},
						yAxis: {
							name: '电影名',
							nameLocation: 'start',
							type: 'category',
							// 是否是反向坐标轴
							inverse: true,
							max: 10,
							// 坐标轴刻度标签的相关设置
							axisLabel: {
								show: true,
								textStyle: {
									fontSize: 12
								},
								formatter: function(value) {
									return value;
								},
								//在 rich 里面，可以自定义富文本样式。利用富文本样式，可以在标签中做出非常丰富的效果。
								rich: {
									flag: {
										fontSize: 12,
										padding: 5
									}
								}
							},
							// 数据更新动画的时长
							animationDuration: 300,
							// 刷新的频率
							animationDurationUpdate: 300
						},
						series: [{
							realtimeSort: true,
							//当使用 dataset 时，seriesLayoutBy 指定了 dataset 中用行还是列对应到系列上，也就是说，系列“排布”到 dataset 的行还是列上。可取值：
							// 'column'：默认，dataset 的列对应于系列，从而 dataset 中每一列是一个维度（dimension）。
							// 'row'：dataset 的行对应于系列，从而 dataset 中每一行是一个维度（dimension）。
							seriesLayoutBy: 'column',
							type: 'bar',
							itemStyle: {
								color: function(param) {
									return countryColors[param.value[1]] || '#5470c6';
								}
							},
							// 可以定义 data 的哪个维度被编码成什么
							encode: {
								// dimension 是预先定义的0，第一列，参看第10行
								x: dimension,
								y: 1
							},
							label: {
								show: true,
								// 文本标签中数值的小数点精度。默认根据当前轴的值自动判断。也可以指定如 2 表示保留两位小数。
								// 本处是在动态变化的时候数字变化的小数精度，此处保留 1 位
								precision: 2,
								position: 'right',
								// 是否开启标签的数字动画。实时修改标签
								valueAnimation: true,
								// 文字的字体系列。
								fontFamily: 'monospace'
							}
						}],
						// Disable init animation. 禁用初始化动画
						animationDuration: updateFrequency,
						animationDurationUpdate: updateFrequency,
						animationEasing: 'linear',
						animationEasingUpdate: 'linear',
						graphic: {
							elements: [{
								type: 'text',
								right: 20,
								bottom: 20,
								style: {
									text: startYear + '日',
									font: 'bolder 60px monospace',
									fill: 'rgba(100, 100, 100, 0.25)'
								},
								z: 100
							}]
						}
					};
					myChart.hideLoading();
					// console.log(option);
					myChart.setOption(option);
					
					for (var i = startIndex; i < years.length - 1; ++i) {
						
						(function(i) {
							setTimeout(function() {
								updateYear(years[i + 1]);	
							}, (i - startIndex) * updateFrequency);
						})(i);
						
					}

					function updateYear(year) {
						var source = data.filter(function(d) {
							return d[2] === year;
						});
						// console.log("source="+source);
						option.series[0].data = source;
						option.graphic.elements[0].style.text = year + '日';
						myChart.setOption(option);
					}

				});

				if (option && typeof option === 'object') {
					myChart.setOption(option);
				}
			},

			getCloudMsg() {
				let vue = this;
				axios.get('http://47.93.220.108:8000/api/v1/movie/emotion')
					.then(response => {
						if (response.data.msg == 'success') {
							console.log("获取词云图数据")
							console.log(response)
							for (let i = 0; i < Object.keys(response.data.res).length; i++) {
								vue.$data.cloudMsg.push({
									value: Object.values(response.data.res)[i],
									name: Object.keys(response.data.res)[i]
								});
							}
						} else {
							console.error("获取机器列表失败")
						}
					})
				console.log('这是词云中的数据')
				console.log(vue.$data.cloudMsg)
				var that = this;
				setTimeout(function () {
				   that.cloud(that.$data.cloudMsg)
				   
				},1000);
				
				//this.cloud()

			},
			cloud(cloudmsg) {
				console.log("开始渲染词云图")
				console.log(cloudmsg)
				var mychart = echarts.init(document.getElementById("cloud"));
				console.log('lll');
				var option = {
					title: {
						text: "电影主题",
						x: "center"
					},
					backgroundColor: "#edffec",
					// tooltip: {
					//   pointFormat: "{series.name}: <b>{point.percentage:.1f}%</b>"
					// },
					series: [{
						type: "wordCloud",
						//用来调整词之间的距离
						gridSize: 20,
						//用来调整字的大小范围
						// Text size range which the value in data will be mapped to.
						// Default to have minimum 12px and maximum 60px size.
						sizeRange: [12, 90],
						// Text rotation range and step in degree. Text will be rotated randomly in range [-90,                                                                             90] by rotationStep 45
						//用来调整词的旋转方向，，[0,0]--代表着没有角度，也就是词为水平方向，需要设置角度参考注释内容
						 rotationRange: [-45, 0, 45, 90],
						 rotationRange: [ 0,90],
						rotationRange: [0, 0],
						//随机生成字体颜色
						// maskImage: maskImage,
						textStyle: {
							normal: {
								color: function() {
									return (
										"rgb(" +
										Math.round(Math.random() * 255) +
										", " +
										Math.round(Math.random() * 255) +
										", " +
										Math.round(Math.random() * 255) +
										")"
									);
								}
							}
						},
						//位置相关设置
						// Folllowing left/top/width/height/right/bottom are used for positioning the word cloud
						// Default to be put in the center and has 75% x 80% size.
						left: "center",
						top: "center",
						right: null,
						bottom: null,
						width: "400%",
						height: "250%",
						//数据
						data: cloudmsg
					}]
				};
				mychart.setOption(option);


			}

		},
	}
</script>

<style>
	.border {
		/* border: 0.0625rem solid #666666; */
		 background-color: #edffec; 
	}
	
</style>
